package com.cxh.mediasessiondemo;

import android.Manifest;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.media.MediaMetadata;
import android.media.browse.MediaBrowser;
import android.media.session.MediaController;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.List;

public class MainClientActivity extends AppCompatActivity {

    private static final int REQ_PERMISSION_CODE = 1;

    private MediaBrowser mMediaBrowser;
    private MediaController mMediaController;
    private MusicUIManager mMusicUIManager;
    private long mLastBackPress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMusicUIManager = new MusicUIManager(this);
        requestNecessaryPermission();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mMediaController) {
            mMediaController.unregisterCallback(mControllerCb);
            mMediaController = null;
        }

        if (null != mMediaBrowser && mMediaBrowser.isConnected()) {
            mMediaBrowser.unsubscribe(mMediaBrowser.getRoot());
            mMediaBrowser.disconnect();
            mMediaBrowser = null;
        }
    }

    @Override
    public void onBackPressed() {
        long currTime = System.currentTimeMillis();
        if (mLastBackPress > 0 && (currTime - mLastBackPress) <= 2000) {
            super.onBackPressed();
        } else {
            mLastBackPress = currTime;
            Toast.makeText(this, "划错了？再划一次？", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (REQ_PERMISSION_CODE == requestCode) {
            int grantedCount = 0;
            for (int i = 0; i < permissions.length; i++) {
                if (PackageManager.PERMISSION_GRANTED == grantResults[i]) {
                    grantedCount++;
                }
            }

            if (grantedCount == permissions.length) {
                connectMediaService();
            }
        }
    }

    private void requestNecessaryPermission() {
        String[] permissions = {
                Manifest.permission.READ_EXTERNAL_STORAGE
        };

        if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            requestPermissions(permissions, REQ_PERMISSION_CODE);
        } else {
            connectMediaService();
        }
    }

    private void connectMediaService() {
        ComponentName componentName = new ComponentName(this, MusicPlayerService.class);
        mMediaBrowser = new MediaBrowser(this, componentName, mConnectionCb, null);
        mMediaBrowser.connect();
    }

    private final MediaBrowser.ConnectionCallback mConnectionCb = new MediaBrowser.ConnectionCallback() {
        @Override
        public void onConnected() {
            super.onConnected();
            if (null != mMediaBrowser && mMediaBrowser.isConnected()) {
                String rootId = mMediaBrowser.getRoot();
                // 订阅
                mMediaBrowser.subscribe(rootId, mSubscriptionCb);
                // 控制端
                mMediaController = new MediaController(MainClientActivity.this,
                        mMediaBrowser.getSessionToken());
                mMediaController.registerCallback(mControllerCb);
                setMediaController(mMediaController);
                mMusicUIManager.setMediaController(mMediaController);
            }
        }

        @Override
        public void onConnectionFailed() {
            super.onConnectionFailed(); // 连接失败
        }

        @Override
        public void onConnectionSuspended() {
            super.onConnectionSuspended(); // 连接断开
        }
    };

    private final MediaBrowser.SubscriptionCallback mSubscriptionCb = new MediaBrowser.SubscriptionCallback() {
        @Override
        public void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowser.MediaItem> children) {
            super.onChildrenLoaded(parentId, children);
            LogUtil.i("SubscriptionCallback.onChildrenLoaded, parentId: " + parentId);
            mMusicUIManager.setDataList(children);
        }

        @Override
        public void onError(@NonNull String parentId) {
            super.onError(parentId);
            LogUtil.e("SubscriptionCallback.onError, parentId: " + parentId);
        }
    };

    private final MediaController.Callback mControllerCb = new MediaController.Callback() {
        @Override
        public void onPlaybackStateChanged(@Nullable PlaybackState state) {
            super.onPlaybackStateChanged(state);
            LogUtil.i("onPlaybackStateChanged, state: " + state);
            if (null != state) {
                mMusicUIManager.onPlaybackStateChanged(state);
            }
        }

        @Override
        public void onMetadataChanged(@Nullable MediaMetadata metadata) {
            super.onMetadataChanged(metadata);
            LogUtil.i("onMetadataChanged, metadata: " + metadata);
            if (null != metadata) {
                mMusicUIManager.onMetadataChanged(metadata);
            }
        }

        @Override
        public void onSessionEvent(@NonNull String event, @Nullable Bundle extras) {
            super.onSessionEvent(event, extras);
            mMusicUIManager.onSessionEvent(event, extras);
        }
    };
}